package org.myproject.persistence.query;

import java.io.Serializable;

public class QueryParam {
	private int first = 0;
	private int count = Integer.MAX_VALUE;
	private Sort[] sort;

	public QueryParam() {

	}

	/**
	 * Constructs a query parameter.
	 * 
	 * @param first
	 *            The row number of the first element in the list.
	 * @param count
	 *            The number of rows to return.
	 * @param sort
	 *            The sort columns.
	 */
	public QueryParam(int first, int count, Sort[] sort) {
		if (first < 0) {
			throw new IllegalArgumentException();
		}
		if (count < 0) {
			throw new IllegalArgumentException();
		}
		this.first = first;
		this.count = count;
		this.sort = sort;
	}

	public int getCount() {
		return count;
	}

	public int getFirst() {
		return first;
	}

	public Sort[] getSort() {
		return sort;
	}

	public void setCount(int count) {
		if (count < 0) {
			throw new IllegalArgumentException();
		}
		this.count = count;
	}

	public void setFirst(int first) {
		if (first < 0) {
			throw new IllegalArgumentException();
		}
		this.first = first;
	}

	public void setSort(Sort[] sort) {
		this.sort = sort;
	}

	/**
	 * Prepends a path (e.g. 'customer.') to the sort data.
	 * 
	 * @param path
	 *            the path that is prepended to the sort data
	 */
	public void prependSortPath(final String path) {
		if (this.sort != null) {
			for (int i = 0; i < this.sort.length; i++) {
				if (this.sort[i] != null) {
					final Sort sort = this.sort[i];
					this.sort[i] = new Sort() {
						public Serializable getData() {
							return path + "." + sort.getData().toString();
						}

						public boolean isAscending() {
							return sort.isAscending();
						}
					};
				}
			}
		}
	}

}